package edu.task.service.impl;

import edu.task.model.SysMsg;
import edu.task.model.SysTask;
import edu.task.model.vo.SysMsgVO;
import edu.task.repository.SysMsgRepository;
import edu.task.repository.SysUserMsgRepository;
import edu.task.repository.SysUserTaskRepository;
import edu.task.service.SysMenuService;
import edu.task.service.SysMsgService;
import edu.task.utils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class SysMsgServiceImpl implements SysMsgService {
    @Autowired
    SysMsgRepository sysMsgRepository;

    @Autowired
    SysUserMsgRepository sysUserMsgRepository;

    @Override
    public List<SysMsg> selectMsgList() {
        return sysMsgRepository.findAll();
    }

    @Override
    @Transactional
    public boolean updateMsg(SysMsgVO msg) {
        Optional<SysMsg> op = sysMsgRepository.findById(msg.getMsgId());
        //判断optional是否为空
        if (!op.isPresent()) {
            return false;
        }
        SysMsg sysMsg = op.get();
        BeanUtils.copyPropertiesIgnoreNull(msg, sysMsg);
        sysMsgRepository.save(sysMsg);
        return null != sysMsg.getMsgId();
    }

    @Override
    @Transactional
    public int deleteMsgById(Long msgId) {
        sysUserMsgRepository.deleteUserMsgById(msgId);
        return sysMsgRepository.deleteMsgById(msgId);
    }

    @Override
    @Transactional
    public int deleteMsgByIds(Long[] msgIds) {
        for (int i=0;i<msgIds.length;i++) {
            sysUserMsgRepository.deleteUserMsgById(msgIds[i]);
            sysMsgRepository.deleteMsgById(msgIds[i]);
        }
        return 1;
    }

    @Override
    public SysMsg selectMsgById(Long msgId) {
        SysMsg sysMsg = new SysMsg();
        sysMsg.setMsgId(msgId);
        return sysMsgRepository.findOne(Example.of(sysMsg)).get();
    }

    @Override
    public List<SysMsg> selectMsgByUserId(Long userId) {
        return sysMsgRepository.selectMsgByUserId(userId);
    }



}
